package com.asktgapp.user.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asktgapp.JGTool.EmojiFilter;
import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.eventbus.PutQuestionsChooseEvent;
import com.asktgapp.model.AddIMGVO;
import com.asktgapp.model.ImgUrlVO;
import com.asktgapp.model.PutQuestionsChooseVO;
import com.asktgapp.modulebase.ServiceUtil;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.user.activity.EngineerListActivity;
import com.asktgapp.user.activity.PutQuestionsChooseTypeActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.utils.SelectPhotoDialogFragment;
import com.jph.takephoto.model.TImage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018-7-21 18:11:35
 * Description:快速提问--提问页面
 */

public class FreeAskPutQuestionsFragment extends BaseFragment {
    private EditText mQuestion, et_version;
    private TextView tvTextNumber, myToolbarRight, myBack, mChooseTypeTv, tv_brand;
    private List allURls = new ArrayList();//所有要展示的url
    private List<ImgUrlVO> imgUrl;
    private int IMGWidth;
    private BaseAdapter mBaseAdapter;
    private RecyclerView mPhotoRecyclerView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_free_ask_putquestions, container, false);
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().getToolbar().setVisibility(View.GONE);
        setHasOptionsMenu(true);

        WindowManager windowManager = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        IMGWidth = display.getWidth() / 5;

        TextView goNotice = rootView.findViewById(R.id.goNotice);
//        goNotice.setText(Html.fromHtml("<font size=\"8sp\" color=\"#618c847e\">如需一对一服务，请</font><font color=\"#FD3722\">【咨询工程师】</font>"));
        goNotice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (checkIsLogin("登录后可查看更多内容"))
                    getActivity().startActivity(new Intent(getActivity(), EngineerListActivity.class));
            }
        });
        mQuestion = rootView.findViewById(R.id.et_question);
        mPhotoRecyclerView = rootView.findViewById(R.id.recycle_photo);
        myToolbarRight = rootView.findViewById(R.id.myToolbarRight);
        myBack = rootView.findViewById(R.id.myBack);
        tvTextNumber = rootView.findViewById(R.id.tvTextNumber);
        mChooseTypeTv = rootView.findViewById(R.id.tv_machine_type);
        tv_brand = rootView.findViewById(R.id.tv_brand);
        et_version = rootView.findViewById(R.id.et_version);
        mQuestion.setFilters(new InputFilter[]{new EmojiFilter()});
        imgUrl = new ArrayList();
        mChooseTypeTv.setOnClickListener(this);
        tv_brand.setOnClickListener(this);
        mPhotoRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        mQuestion.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                tvTextNumber.setText(String.valueOf(s.length()));
            }
        });
        myBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getBaseActivity().onBackPressed();
            }
        });


        myToolbarRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                String question = mQuestion.getText().toString().trim();
                if (TextUtils.isEmpty(question)) {
                    showTost("问题描述最少十个字！", 0);
                    return;
                }
                if (question.length() < 10) {
                    showTost("问题描述最少十个字！", 0);
                    return;
                }
                if (question.length() > 500) {

                    return;
                }
                if (!Utils.noContainsEmoji(question)) {
                    showTost("不支持输入emoji表情", 1);
                    return;
                }

                hideSoftKeyboard();
                doCommit();
            }
        });

        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = null;
                if (viewType == 0) {
                    //本地图片
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_select_photo, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {
                            ImageView imageView = holder.getView(R.id.img);
                            final ImageView delete = holder.getView(R.id.iv_delete);
                            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
                            params.width = IMGWidth;
                            params.height = IMGWidth;
                            imageView.setLayoutParams(params);
                            if (data instanceof ImgUrlVO) {
                                final ImgUrlVO bean = (ImgUrlVO) data;
                                ImageDisplayUtil.LoadDisImage(getActivity(), imageView, bean.getUrl());
                                delete.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        imgUrl.remove(bean);
                                        setAdpterData();
                                    }
                                });
                            }
                        }

                        @Override
                        public void onItemClick(View view, int position) {

                        }
                    });
                } else if (viewType == 1) {
                    //添加
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_picture_add, parent, false), new BaseViewHolder.Callbacks() {
                        @Override
                        public void bind(BaseViewHolder holder, Object data) {
                            ImageView imageView = holder.getView(R.id.img);
                            FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) imageView.getLayoutParams();
                            params.width = IMGWidth;
                            params.height = IMGWidth;
                            imageView.setLayoutParams(params);
                        }

                        @Override
                        public void onItemClick(View view, int position) {
                            onPickPhoto();

                        }
                    });
                }
                return holder;

            }

            @Override
            public int getItemViewType(int position) {
                Object bean = mBaseAdapter.getData().get(position);
                if (bean instanceof ImgUrlVO) {
                    return 0;
                } else if (bean instanceof AddIMGVO) {
                    return 1;
                } else return 0;

            }
        };
        mPhotoRecyclerView.setAdapter(mBaseAdapter);
        setAdpterData();

    }

    private void onPickPhoto() {
        SelectPhotoDialogFragment selectPhotoDialogFragment = new SelectPhotoDialogFragment(new SelectPhotoDialogFragment.setResult() {
            @Override
            public void setResult(ArrayList<TImage> mImages) {
                for (TImage img : mImages) {
                    ImgUrlVO bean = new ImgUrlVO(img.getPath());
                    imgUrl.add(bean);
                }
                setAdpterData();
            }
        }, 3 - imgUrl.size());
        selectPhotoDialogFragment.show(getFragmentManager(), "selectPhotoDialogFragment");
    }

    public void setAdpterData() {
        allURls.clear();
        if (imgUrl.size() > 0) {
            allURls.addAll(imgUrl);
        }
        mBaseAdapter.setData(allURls);
        if (allURls.size() < 3) {
            mBaseAdapter.addData(BaseAdapter.AddType.LASE, new AddIMGVO());
        }
    }

    private void doCommit() {
        myToolbarRight.setClickable(false);
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        ApiUtil.putDefultData(getActivity(), params);
        String title="";
        if (chooseVO != null) {
            if (!TextUtils.isEmpty(chooseVO.getSeriesId()))
                params.put("seriesId", RequestBody.create(ServiceUtil.MULTIPART, chooseVO.getSeriesId()));
            if (!TextUtils.isEmpty(chooseVO.getModelId()))
                params.put("modelId", RequestBody.create(ServiceUtil.MULTIPART, chooseVO.getModelId()));
            if (!TextUtils.isEmpty(chooseVO.getBrandId()))
                params.put("brandId", RequestBody.create(ServiceUtil.MULTIPART, chooseVO.getBrandId()));
           title="设备型号："+ chooseVO.getTypeName() +"  "+ chooseVO.getBrandName()+"  " + chooseVO.getModelName()+"\n故障描述：";
        }

        params.put("content", RequestBody.create(ServiceUtil.MULTIPART, title+mQuestion.getText().toString().trim()));
        List<String> url = new ArrayList<>();
        for (ImgUrlVO vo : imgUrl) {
            url.add(vo.getUrl());
        }
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.freeSubQuestion(params, ApiUtil.files2Parts("problePic", url.toArray(), ApiUtil.MULTIPART));
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                myToolbarRight.setClickable(true);
                dismissProgress();
                if (response.isSuccessful()) {
                    showTost("提问成功", 0);
                    Intent intent = new Intent(getActivity(), com.asktgapp.user.activity.QuestionActivity.class);
                    intent.putExtra("positon", 1);
                    startActivity(intent);
                    getActivity().finish();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                myToolbarRight.setClickable(true);
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }

            }
        });

        // TODO: 2018/1/24 调用接口上传问题
    }

    @Override
    public void loadData() {
//        Apiservice apiservice = ApiUtil.getInstance().create();
//        HashMap params = new HashMap();
//        Call<ApiResponseBody<List<DeviceTypeVO>>> call = apiservice.getTypeList(params);
//        call.enqueue(new Callback<ApiResponseBody<List<DeviceTypeVO>>>() {
//            @Override
//            public void onResponse(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Response<ApiResponseBody<List<DeviceTypeVO>>> response) {
//                if (response.isSuccessful()) {
//                    mTypeList = response.body().getResult();
//                } else {
//                    showTost(response.raw().message(), 1);
//                }
//            }
//
//            @Override
//            public void onFailure(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Throwable t) {
//                ApiException apiException = ExceptionHandle.handleException(t);
//                showTost(apiException.getMessage(), 1);
//            }
//        });
    }


    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();

    }

    private PutQuestionsChooseVO chooseVO;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void hasHomeEvent(PutQuestionsChooseEvent chooseEvent) {
        if (chooseEvent != null) {
            chooseVO = chooseEvent.getChooseVO();
            if (chooseVO != null) {
                mChooseTypeTv.setText(chooseVO.getTypeName() +"  "+ chooseVO.getBrandName() +"  "+ chooseVO.getModelName());
            }
        }
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_machine_type:
                Intent intent = new Intent(getActivity(), PutQuestionsChooseTypeActivity.class);
                intent.putExtra("isPutQuestions", true);
                startActivity(intent);
                break;
            case R.id.tv_brand:
//                if (Util.isEmpty(mChooseTypeTv.getText().toString().trim())) {
//                    showTost("请先选择设备类型", 1);
//                    return;
//                }
//                Intent intent = new Intent(getActivity(), ChooseBrandActivity.class);
//                intent.putExtra("typeId", mSelectedTypeId);
//                startActivityForResult(intent, 200);
                break;
        }
    }


}
